package com.cuz.hot100;

import java.util.ArrayList;
import java.util.List;

public class Q54SpiralMatrix {
    public static void main(String[] args) {
        int[][] ints = {
                {1, 2, 3, 4},
                {5, 6, 7, 8},
                {9, 10, 11, 12},
        };
        System.out.println(spiralOrder1(ints));
    }

    public static List<Integer> spiralOrder1(int[][] matrix) {
        int topBoundary = 0;
        int downBoundary = matrix.length - 1;
        int leftBoundary = 0;
        int rightBoundary = matrix[0].length - 1;
        ArrayList<Integer> res = new ArrayList<>();
        while (true) {
            for (int col = leftBoundary; col <= rightBoundary; col++) {
                res.add(matrix[topBoundary][col]);
            }
            topBoundary++;
            if (topBoundary > downBoundary) {
                break;
            }
            for (int row = topBoundary; row <= downBoundary; row++) {
                res.add(matrix[row][rightBoundary]);
            }
            rightBoundary--;
            if (rightBoundary < leftBoundary) {
                break;
            }
            for (int col = rightBoundary; col >= leftBoundary; col--) {
                res.add(matrix[downBoundary][col]);
            }
            downBoundary--;
            if (topBoundary > downBoundary) {
                break;
            }
            for (int row = downBoundary; row >= topBoundary; row--) {
                res.add(matrix[row][leftBoundary]);
            }
            leftBoundary++;
            if (rightBoundary < leftBoundary) {
                break;
            }
        }
        return res;
    }


}
